import 'dart:async';

class AsyncTimer {
  AsyncTimer(this.interval, this.callback) {
    _innerTimer = Timer(Duration.zero, _onTick);
  }

  final Duration interval;
  final Future<dynamic> Function(AsyncTimer timer) callback;

  late Timer _innerTimer;

  bool get isActive => _isActive;
  bool _isActive = true;

  void cancel() {
    _isActive = false;
    _innerTimer.cancel();
  }

  void _onTick() {
    callback(this).whenComplete(_didTick);
  }

  void _didTick() {
    if (isActive) {
      // schedule the next callback
      _innerTimer = Timer(interval, _onTick);
    }
  }
}
